package edu.ycu.aladdin.web.controller;

import edu.ycu.aladdin.web.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author <a href="mailto:wangruihuano@gmail.com">王瑞环</a>
 * @since 1.0
 */
public abstract class AbsController {

    public static final String COOKIE_LOGIN_KEY = "sso";
    public static final String COOKIE_OAUTH_CHANNLE = "coc";
    public static final String REDIRECT = "redirect:";
    protected static final String REDIRECT_INDEX = HttpUtils.createRedirectHtml("/index.html");

    @Value("${aladdin.session.timeout}")
    private int sessionTimeout;

    private String cookie_domain = "/";

    protected void setCookie(String key, String value, int maxAge, String path,
                             HttpServletResponse response) {

        Cookie cookie = new Cookie(key, value);

        cookie.setPath(path);
        if (maxAge > 0) {
            cookie.setMaxAge(maxAge);
        }
        response.addCookie(cookie);
    }

    protected void setCookie(String key, String value, HttpServletResponse response) {
        setCookie(key, value, -1, "/",response);
    }

    /**
     * 设置登录的cookie
     *
     * @param sessionId
     * @param response
     */
    protected void setLoginCookie(String sessionId, HttpServletResponse response) {
        setCookie(COOKIE_LOGIN_KEY, sessionId, sessionTimeout * 60, "/",response);
    }

    /**
     * 重定向
     * @param url 重定向地址
     * @return
     */
    protected String redirect(String url){
        return REDIRECT + url;
    }
}
